package storage.v1;

import java.util.ArrayList;
import java.util.Map;

import com.onpositive.commons.platform.registry.IAdaptable2;
import com.onpositive.data.IPropertyConstants;
import com.onpositive.mediawiki.propertyparser.ParsedDocument;
import com.onpositive.units.ParsedProperty;
import com.onpositive.units.ParsedString;
import com.onpositive.units.ParsedValue;
import com.onpositive.units.ParsedValueSequenceV2;

public class WikiStructureExtractor extends AbstractValueExtractor {

	
	@Override
	public void process(String text, ParsedDocument pDoc,IParserProvider parserProvider, IAdaptable2 adaptable)
	{
		ArrayList<String> list = new ArrayList<String>();
		int prev=0;
		int l = text.length();
		for( int i = text.indexOf("[[") ; i>=0&&i < l; i = text.indexOf("[[", prev)){
			
			prev = i + "[[".length();
			boolean gotDot=false;
			while(prev<l){
				char ch = text.charAt(prev);
				gotDot |= (ch==':');
				
				if(text.startsWith("]]",prev)){
					prev+="]]".length();
					break;
				}
				prev++;
			}
			if(!gotDot)
				continue;
			
			list.add(text.substring(i, prev));
		}
		if(list.isEmpty())
			return;
		
		String propName = IPropertyConstants.WIKI_STRUCTURE_LINKS_PROPERTY_NAME;
		ParsedProperty prop = pDoc.getProperty(propName);
		if(prop==null){
			prop=new ParsedProperty(propName);
			pDoc.addProperty(prop);
		}
		ArrayList<ParsedValue> pvList = new ArrayList<ParsedValue>();
		for(String s : list){
			ParsedString ps = new ParsedString(s, getDefaultComment());
			pvList.add(ps);
		}
		ParsedValueSequenceV2 pvs = new ParsedValueSequenceV2(pvList.toArray(new ParsedValue[pvList.size()]), getDefaultComment(), null);
		prop.addValue(pvs);
	}

	@Override
	public void dispose() {}

	@Override
	public void configure(Map<String, Object> params) {}

}
